part of base_package;

// ignore: must_be_immutable
typedef OnCallBack = void Function();

class FormWidget extends StatefulWidget {
  /// ------------------公共参数------------------

  /// 是否显示星号，默认：false
  bool isStar;

  /// 星号样式，默认：Colors.red，16.sp
  TextStyle? starStyle;

  /// 左边文字样式，默认：Colors.grey，16.sp
  TextStyle? leftTextStyle;

  /// 右边文字样式，默认：Colors.black，16.sp
  TextStyle? rightTextStyle;

  /// 左边数据
  String leftData;

  /// 右边数据，传入一个map，用rightValue区别
  Map rightData;

  /// 右边数据key值
  String? rightKey;

  /// 右边数据value值
  String rightValue;

  /// 表单类型，-1，显示文本，0 输入框，1 Map选择（单选），2 时间选择，3 带搜索Map选择（单选）
  int type;

  /// 表单是否可以编辑，true 可以编辑，false 不能编辑，默认：true
  bool isEdit;

  /// 变化回调通知
  OnCallBack? onCallBack;

  /// 是否进行时间格式化，只对-1，显示文本起作用
  bool isTimeFormat;

  /// ------------------输入框参数------------------

  /// 输入框文字提示样式，默认：Colors.grey，16.sp
  TextStyle? hintStyle;

  /// 输入框文字提示，默认：请输入
  String? hintText;

  /// 输入类型 0 文本，1 整数，2 小数
  int inputType;

  /// 是否是密码模式，默认：false
  bool isPassword;

  /// 输入框控制器
  TextEditingController? controller;

  /// ------------------Map选择（单选）参数------------------

  /// Map选择列表数据
  List? selectList;

  /// Map选择列表数据选择的key
  String? selectListKey;

  /// Map选择列表数据显示的value
  String? selectListName;

  /// ------------------时间选择参数------------------

  /// true 日期时间选择，false 日期选择，默认：true
  bool isTime;

  /// 最小时间
  DateTime? minTime;

  /// 最大时间
  DateTime? maxTime;

  /// 时间格式化
  String timeFormat;

  FormWidget({
    Key? key,
    this.isStar = false,
    this.starStyle,
    this.inputType = 0,
    this.leftTextStyle,
    this.rightTextStyle,
    this.hintStyle,
    this.hintText,
    required this.leftData,
    required this.rightData,
    required this.rightValue,
    this.type = 0,
    this.isEdit = true,
    this.selectList,
    this.selectListKey,
    this.selectListName,
    this.rightKey,
    this.isTime = true,
    this.minTime,
    this.maxTime,
    this.onCallBack,
    this.isPassword = false,
    this.controller,
    this.timeFormat = 'yyyy-MM-dd hh:mm:ss',
    this.isTimeFormat = false,
  }) : super(key: key);

  @override
  _FormWidget createState() => _FormWidget();
}

class _FormWidget extends State<FormWidget> {
  /// --------------显示文本---------------
  textWidget() {
    return SizedBox(
        width: 160.w,
        child: Text(
            widget.isTimeFormat
                ? timeFormatF(widget.rightData[widget.rightValue] ?? '')
                : '${widget.rightData[widget.rightValue] ?? ''}',
            textAlign: TextAlign.right,
            style: widget.rightTextStyle ??
                TextStyle(color: Colors.black, fontSize: 16.sp)));
  }

  /// --------------输入框---------------

  late TextEditingController controller;

  /// 键盘类型，0 文本，1 整数，2 小数
  TextInputType inputTypeF() {
    if (widget.inputType == 1) return TextInputType.number;
    if (widget.inputType == 2) return TextInputType.number;
    return TextInputType.text;
  }

  /// 限定输入类型 0 文本，1 整数，2 小数
  List<TextInputFormatter>? inputFormattersF() {
    if (widget.inputType == 1) {
      return [FilteringTextInputFormatter.allow(RegExp("[0-9]"))];
    }
    if (widget.inputType == 2) return [UsNumberTextInputFormatter()];
    return null;
  }

  /// 输入框
  Widget textField() {
    return SizedBox(
      width: 160.w,
      child: TextField(
        enabled: widget.isEdit,
        autofocus: false,
        obscureText: widget.isPassword,
        keyboardType: inputTypeF(),
        inputFormatters: inputFormattersF(),
        onChanged: (String text) {
          widget.rightData[widget.rightValue] = text;
          if (widget.onCallBack != null) widget.onCallBack!();
        },
        controller: controller,
        textAlign: TextAlign.end,
        maxLines: 1,
        style: widget.rightTextStyle ??
            TextStyle(color: Colors.black, fontSize: 16.sp),
        decoration: InputDecoration(
            isCollapsed: true, // 包裹内容来设置TextField高度
            hintStyle: widget.hintStyle ??
                TextStyle(color: Colors.grey, fontSize: 16.sp),
            hintText: widget.hintText ?? '请输入',
            border: InputBorder.none),
      ),
    );
  }

  /// --------------Map选择（单选）--------------
  /// --------------时间选择--------------

  /// 所选索引
  int selectMapIndex = 0;

  /// 选择Widget
  Widget selectWidget() {
    return Row(
      children: [
        SizedBox(
          width: 150.w,
          child: Text(
            timeFormatF(widget.rightData[widget.rightValue] ?? ''),
            textAlign: TextAlign.end,
            style: widget.rightTextStyle ??
                TextStyle(color: Colors.black, fontSize: 16.sp),
          ),
        ),
        widget.isEdit
            ? Icon(Icons.navigate_next,
                color: widget.rightTextStyle == null
                    ? Colors.black
                    : widget.rightTextStyle?.color ?? Colors.black)
            : Container(),
      ],
    );
  }

  /// Map选择（单选）方法
  selectMapF(BuildContext context) {
    // 收起键盘，失去焦点
    FocusManager.instance.primaryFocus?.unfocus();
    if (widget.selectList == null || widget.selectList!.isEmpty) {
      '选择列表为空（selectList）'.toast();
      return;
    }
    if (widget.selectListKey == null || widget.selectListKey!.isEmpty) {
      '选择列表key为空（selectListKey）'.toast();
      return;
    }
    if (widget.selectListName == null || widget.selectListName!.isEmpty) {
      '选择列表显示名称name为空（selectListName）'.toast();
      return;
    }
    if (widget.selectListName == null || widget.selectListName!.isEmpty) {
      '右边数据key为空（rightKey）'.toast();
      return;
    }
    DialogFactory.pickerMap(context, widget.selectList!, widget.selectListName!,
        initialItem: selectMapIndex, onConfirm: (confirmData, mIndex) {
      selectMapIndex = mIndex;
      widget.rightData[widget.rightKey] = confirmData[widget.selectListKey];
      widget.rightData[widget.rightValue] = confirmData[widget.selectListName];
      if (widget.onCallBack != null) widget.onCallBack!();
    }, onCancel: () {});
  }

  /// Map选择（单选）,带搜索方法
  selectSearchMapF(BuildContext context) {
    // 收起键盘，失去焦点
    FocusManager.instance.primaryFocus?.unfocus();
    if (widget.selectList == null || widget.selectList!.isEmpty) {
      '选择列表为空（selectList）'.toast();
      return;
    }
    if (widget.selectListKey == null || widget.selectListKey!.isEmpty) {
      '选择列表key为空（selectListKey）'.toast();
      return;
    }
    if (widget.selectListName == null || widget.selectListName!.isEmpty) {
      '选择列表显示名称name为空（selectListName）'.toast();
      return;
    }
    if (widget.selectListName == null || widget.selectListName!.isEmpty) {
      '右边数据key为空（rightKey）'.toast();
      return;
    }
    DialogFactory.pickerSearchMap(
        context, widget.selectList!, widget.selectListName!,
        onConfirm: (confirmData, mIndex) {
      widget.rightData[widget.rightKey] = confirmData[widget.selectListKey];
      widget.rightData[widget.rightValue] = confirmData[widget.selectListName];
      if (widget.onCallBack != null) widget.onCallBack!();
    }, onCancel: () {});
  }

  @override
  void initState() {
    controller = widget.controller ?? TextEditingController();
    if (widget.type == 0) {
      controller.text = widget.rightData[widget.rightValue] ?? '';
    }
    super.initState();
  }

  /// 时间选择方法
  selectTimeF(BuildContext context) {
    // 收起键盘，失去焦点
    FocusManager.instance.primaryFocus?.unfocus();
    if (widget.isTime) {
      DialogFactory.dateTimeSelect(context,
          minTime: widget.minTime, maxTime: widget.maxTime, onTime: (time) {
        widget.rightData[widget.rightValue] = timeFormatF(time);
        if (widget.onCallBack != null) widget.onCallBack!();
      });
    } else {
      DialogFactory.dateSelect(context,
          minTime: widget.minTime, maxTime: widget.maxTime, onTime: (time) {
        widget.rightData[widget.rightValue] = timeFormatF(time);
        if (widget.onCallBack != null) widget.onCallBack!();
      });
    }
  }

  @override
  void dispose() {
    controller.clear();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: () => itemClick(context),
      child: Container(
        color: Colors.white,
        padding: EdgeInsets.symmetric(vertical: 12.w, horizontal: 8.w),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              widget.leftData,
              style: widget.leftTextStyle ??
                  TextStyle(color: Colors.grey, fontSize: 16.sp),
            ),
            widget.isStar
                ? Text(
                    ' * ',
                    style: widget.starStyle ??
                        TextStyle(color: Colors.red, fontSize: 16.sp),
                  )
                : Container(),
            Expanded(child: Container()),
            rightWidget(),
          ],
        ),
      ),
    );
  }

  /// 表单类型，-1，显示文本，0 输入框，1 Map选择（单选），2 时间选择，3 带搜索Map选择（单选）
  Widget rightWidget() {
    if (widget.type == -1) return textWidget();
    if (widget.type == 1) return selectWidget();
    if (widget.type == 2) return selectWidget();
    if (widget.type == 3) return selectWidget();
    return textField();
  }

  // 表单条目点击
  itemClick(BuildContext context) {
    if (!widget.isEdit) return;
    if (widget.type == 0) return;
    if (widget.type == 1) selectMapF(context);
    if (widget.type == 2) selectTimeF(context);
    if (widget.type == 3) selectSearchMapF(context);
    // if (widget.type == 4) selectSearchCheckboxF(context);
  }

  /// 搜索多选
  selectSearchCheckboxF(BuildContext context) {
    // 收起键盘，失去焦点
    FocusManager.instance.primaryFocus?.unfocus();
    // Util.pickerSearchCheckboxMap(
    //     context, widget.selectList ?? [], widget.selectListName ?? '',
    //     onConfirm: (confirmData) {
    //   itemString = '';
    //   setState(() {
    //     for (Map data in confirmData) {
    //       itemString += '${data[widget.selectListName ?? '']},';
    //     }
    //     itemString = itemString.substring(0, itemString.length - 1);
    //   });
    //   if (widget.selectCheckboxCallback != null)
    //     widget.selectCheckboxCallback!(confirmData);
    // }, onCancel: () {});
  }

  /// 时间数据格式化方法
  /// yyyy-MM-dd hh:mm:ss
  String timeFormatF(String rightData) {
    if (widget.isTime) {
      if (rightData.length < 19) {
        return rightData;
      }
      if (!widget.timeFormat.contains('ss')) {
        // yyyy-MM-dd hh:mm
        return rightData.substring(0, 16);
      } else if (!widget.timeFormat.contains('mm')) {
        // yyyy-MM-dd hh
        return rightData.substring(0, 13);
      }
    } else {
      if (rightData.length < 10) {
        return rightData;
      }
      if (!widget.timeFormat.contains('hh')) {
        // yyyy-MM-dd
        return rightData.substring(0, 10);
      } else if (!widget.timeFormat.contains('dd')) {
        // yyyy-MM
        return rightData.substring(0, 7);
      } else if (!widget.timeFormat.contains('MM')) {
        // yyyy
        return rightData.substring(0, 4);
      }
    }

    return rightData;
  }
}
